# Build stage
FROM node:18-alpine AS build-stage

WORKDIR /app

# Copy package files first to leverage Docker cache
COPY package*.json ./
RUN npm ci

# Copy the rest of the app and build
COPY . .
RUN npm run build && npm cache clean --force

# Production stage
FROM nginx:stable-alpine

# Copy built app
COPY --from=build-stage /app/dist /usr/share/nginx/html

# Create nginx config for SPA routing
RUN rm /etc/nginx/conf.d/default.conf && \
    echo 'server { \
    listen 80; \
    server_name _; \
    root /usr/share/nginx/html; \
    index index.html; \
    location / { \
        try_files $uri $uri/ /index.html; \
    } \
    # Disable access logs for static assets \
    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ { \
        expires max; \
        log_not_found off; \
        access_log off; \
    } \
}' > /etc/nginx/conf.d/default.conf

# Remove unused directories to reduce attack surface
RUN rm -rf /usr/share/nginx/html/*.map && \
    rm -rf /etc/nginx/templates/ && \
    rm -rf /docker-entrypoint.d/ && \
    rm -rf /var/cache/apk/*

# Set correct permissions
RUN chown -R nginx:nginx /usr/share/nginx/html && \
    chmod -R 755 /usr/share/nginx/html

# Container metadata
LABEL maintainer="Maintainer" \
      description="Frontend for Agent Management Platform" \
      version="1.0"

# Health check (with appropriate user permissions)
HEALTHCHECK --interval=30s --timeout=3s CMD wget -q --spider http://localhost/ || exit 1

EXPOSE 80

# Use the official nginx entrypoint script
CMD ["nginx", "-g", "daemon off;"]
